﻿var _helper = new Helper();
var editIndex = undefined;
var oldvalue = -1;
var newvalue = -1;
jQuery(document).ready(function () {

    jQuery('#queueMenu').addClass('active');
    jQuery('#queueAllList').datagrid({
        url: "/service/api.ashx?metdhodName=GetQueueAll",
        onSelect: onRowSelected,
        onBeforeEdit: onBeginEditStart,
        onAfterEdit: onEndEdit,
        onDblClickCell: function (index, field1) {

            if (editIndex != undefined) {
                //jQuery('#orderDetailsList').datagrid('select', editIndex);
                var t = jQuery('#queueAllList'); //My treegrid selector
                t.datagrid('endEdit', editIndex);
                editIndex = undefined;
                return;
            }
            editIndex = index;

            jQuery(this).datagrid('selectRow', index).datagrid('editCell', { index: index, field: field1 });
            var ed = jQuery(this).datagrid('getEditor',
                                     { index: index, field: field1 });
            if (ed == null) {
                return;
            }
            jQuery(ed.target).focus().select().bind('keyup', function (e) {
                var code = e.keyCode || e.which;
                if (code == 13) { //Enter keycode
                    //Trigger code to save row
                    //This executes onAfterEdit event code
                    var t = jQuery('#queueAllList'); //My treegrid selector
                    t.datagrid('endEdit', editIndex, field1);
                    editIndex = undefined; //editIndex is a global var

                }
            });
        }

    });

    jQuery('#queueAllList').datagrid('enableFilter', [

        {
            field: 'TotalQty',
            type: 'numberbox',
            op: ['equal', 'notequal', 'less', 'greater']
        },
        {
            field: 'id',
            type: 'hidefilter',

        },
        {
            field: 'Date',
            type: 'hidefilter'
        },
        {
            field: 'Rate',
            type: 'hidefilter'
        },
        {
            field: 'ValidFrom',
            type: 'hidefilter'
        },
         {
             field: 'ValidTo',
             type: 'hidefilter'
         },
         {
             field: 'IsActive',
             type: 'hidefilter'
         }
    ]

    );

    //setInterval(grid_refresh, 60000); // schedule next refresh after 15sec
});

function grid_refresh() {
    jQuery('#queueAllList').datagrid('reload');
}

function onBeginEditStart(index, row) {
    oldvalue = row.Qty;
}

function onEndEdit(i, row, changed) {
    if (changed.Qty > oldvalue) {
        alert("ไม่สามารถ revise qty มากกว่าค่าปัจจุบันได้");
        jQuery('#queueAllList').datagrid('updateRow', {
            index: i,
            row: {
                Qty: oldvalue
            }
        });
        return false;
    }
    if (!jQuery.isEmptyObject(changed)) {
        updateQueueList.push(row);
    }
}

//function pagerFilter(data) {
//    if (typeof data.length == 'number' && typeof data.splice == 'function') {	// is array
//        data = {
//            total: data.length,
//            rows: data
//        }
//    }
//    var dg = jQuery(this);
//    var opts = dg.datagrid('options');
//    var pager = dg.datagrid('getPager');
//    pager.pagination({
//        onSelectPage: function (pageNum, pageSize) {
//            opts.pageNumber = pageNum;
//            opts.pageSize = pageSize;
//            pager.pagination('refresh', {
//                pageNumber: pageNum,
//                pageSize: pageSize
//            });
//            dg.datagrid('loadData', data);
//        }
//    });
//    if (!data.originalRows) {
//        data.originalRows = (data.rows);
//    }
//    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
//    var end = start + parseInt(opts.pageSize);
//    data.rows = (data.originalRows.slice(start, end));
//    return data;
//}

jQuery.extend(jQuery.fn.datagrid.methods, {
    editCell: function (jq, param) {
        return jq.each(function () {
            var opts = jQuery(this).datagrid('options');
            var fields = jQuery(this).datagrid('getColumnFields', true).concat(jQuery(this).datagrid('getColumnFields'));
            for (var i = 0; i < fields.length; i++) {
                var col = jQuery(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field) {
                    col.editor = null;
                }
            }
            jQuery(this).datagrid('beginEdit', param.index);
            for (var i = 0; i < fields.length; i++) {
                var col = jQuery(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

var updateQueueList = [];

//function endEditing() {
//    if (editIndex == undefined) { return true }
//    if (jQuery('#queueAllList').datagrid('validateRow', editIndex)) {
//        jQuery('#queueAllList').datagrid('endEdit', editIndex);
//        //var rowEdited = jQuery('#queueAllList').datagrid('getRows')[editIndex];
//        //updateQueueList.push(rowEdited);


//        editIndex = undefined;
//        return true;
//    } else {
//        return false;
//    }
//}

function updateQueueStatus(IsEnable) {
    var rowUpdating = jQuery('#queueAllList').datagrid('getSelected');
    if (rowUpdating == undefined || rowUpdating == null) {
        return;
    }
    var isDisable = "disable";
    if (!rowUpdating.IsActive) {
        isDisable = "enable";
    }

    jQuery.messager.confirm('Confirm', 'Are you sure you want to <b>' + isDisable + '</b> on Mat No ' + rowUpdating.ProductCode + ' in Order No ' + rowUpdating.OrderNo + ')?', function (r) {
        if (r) {
            _helper.UpdateQueueStatus(rowUpdating.id, IsEnable, function (result) {
                if (result.responseText) {
                    alert(result.responseText);
                    jQuery('#queueAllList').datagrid('reload');
                }
                updateStatusBar(result.responseText)
            });
        }
    });
}

function updateQueue() {

    if (updateQueueList == undefined || updateQueueList.length == 0) {
        return;
    }
    var row = JSON.stringify(updateQueueList);
    var updateMsg = '';
    jQuery.each(updateQueueList, function (i, d) {
        updateMsg += 'MatNo ' + d.ProductCode + ' of ' + d.OrderNo + '<br>';
    });

    jQuery.messager.confirm('Confirm', 'Are you sure you want to update <br>' + updateMsg , function (r) {
        if (r) {
            _helper.UpdateQueue(row, function (result) {
                if (result.responseText) {
                    alert(result.responseText);
                    jQuery('#queueAllList').datagrid('reload');
                    updateQueueList = [];
                }
                updateStatusBar(result.responseText)
            });
        }
    });
}

function deleteQueue() {

    var rowDeleting = jQuery('#queueAllList').datagrid('getSelected');
    if (rowDeleting == undefined || rowDeleting == null) {
        alert("please select queue to delete");
        return;
    }

    var row = JSON.stringify(rowDeleting);

    jQuery.messager.confirm('Confirm', 'Are you sure you want to delete Queues on MatNo ' + rowDeleting.ProductCode + ' of DocNo ' + rowDeleting.OrderNo + '?', function (r) {
        if (r) {
            _helper.DeleteQueue(row, function (result) {
                if (result.responseText) {
                    alert(result.responseText);
                    jQuery('#queueAllList').datagrid('reload');
                }
                updateStatusBar(result.responseText)
            });
        }
    });
}



//function onDblClickCell(index, field) {
//    if (endEditing()) {
//        jQuery('#queueAllList').datagrid('selectRow', index)
//                .datagrid('editCell', { index: index, field: field });
//        editIndex = index;
//    }
//}

function onRowSelected(i, r) {
    var row = r;
    if (r.IsActive == true) {
        jQuery('#queuePause').linkbutton('enable');
        jQuery('#queueResume').linkbutton('disable');
    }
    else {
        jQuery('#queuePause').linkbutton('disable');
        jQuery('#queueResume').linkbutton('enable');
    }
}

function formatBoolean(val, rec) {
    if (val) {
        return '<span class="icon-ok"></span>';
    } else {
        return '<span class="icon-no"></span>';
    }
}

function formatDelete(val, rec) {
    if (val) {
        return '<span style="color:red;">Delete</span>';
    } else {
        return '<span></span>';
    }
}

function formatRemaining(val, data, index) {
    if (data.IsReviseQtyFromQueue === null || data.IsReviseQtyFromQueue === '') {
        return val;
    }
    else {
        return '<span style="color:red;">' + val + '</span>';
    }
}

function formatPlantChanged(val, data, index) {
    if (data.IsRevisePlantFromQueue === null || data.IsRevisePlantFromQueue === '') {
        return val;
    }
    else {
        return '<span style="color:red;">' + val + '</span>';
    }
}


function formatQty(val) {

    if (val < 0) {
        return '<span style="color:red;">(' + val + ')</span>';
    } else {
        return val;
    }
}

var matnoQueueSelection;
function formatLinkTransectionDetail(val, data, index) {
    if (matnoQueueSelection != undefined && matnoQueueSelection == data.ItemId) {
        return "<a href=javascript:openTransectionPopup('" + data.OrderNo + "','" + data.ItemId + "');>ดู Transaction details</a>"
    }
}

function formatLinkOrderDetail(val, data, index) {
    return "<a href=javascript:OpenOrderDetailsPopup('" + data.OrderNo + "','" + data.ProductCode + "');>ดู Order details</a>"
}

function formatSpecialRate(val, all) {

    if (val != all.DefaultPercent) {
        return '<span style="color:red;">' + val + '</span>';
    } else {
        return val;
    }
}

function OpenOrderDetailsPopup(orderID, Matno) {
    matnoQueueSelection = Matno;
    jQuery('#orderDetailsList').datagrid({
        url: "/service/api.ashx?metdhodName=GetOrderDetails&orderId=" + orderID + "&status=3",
        pagination: false

    });

    jQuery('#orderDetailsList').attr("orderno", orderID);
    jQuery('#orderDetails').dialog('open').dialog('setTitle', 'รายละเอียดใบสั่งซื้อเลขที่ ' + orderID);
}

function openTransectionPopup(orderNo, MatNo) {
    _helper.GetTransectionByOrderNoAndMat(orderNo, MatNo, function (transectionData) {
        var transectionDetail = jQuery('#transectionDetailsList');
        transectionDetail.attr("orderno", orderNo);
        transectionDetail.attr("MatNo", MatNo);
        var currentQty = 0;
        transectionDetail.datagrid({
            data: transectionData
        });

        for (var i = 0; i < transectionData.length; i++) {
            currentQty += parseFloat(transectionData[i].Qty);
        }

        transectionDetail.datagrid('reloadFooter', [{ Plant: 'Total', Qty: currentQty }]);
        jQuery('#transectionDetails').dialog('open').dialog('setTitle', 'รายละเอียด Transection');
    });


}